package com.hdoit.ares.web.cust.wechat;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.RedEnvelopeRecord;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IGoldenBeanDetailService;
import com.hdoit.ares.logical.acc.service.IRedEnvelopeRecordService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.acti.service.IActiTaskService;
import com.hdoit.ares.logical.app.service.IAppRemindMessageService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.enums.AresManageContainer;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeRecordType;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeStatusType;
import com.hdoit.ares.selfcommon.enums.cust.AttentionStatus;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.hdoit.ares.selfcommon.enums.order.GoodsMark;
import com.hdoit.ares.selfcommon.jpush.JpushClient;
import com.hdoit.ares.web.wechat.WechatTemplateManager;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.logical.systask.service.ISmsSendService;
import com.tennetcn.common.logical.viewmodel.wechat.WechatOrderGoodsSearch;
import com.tennetcn.common.logical.wechat.model.WechatOrder;
import com.tennetcn.common.logical.wechat.model.WechatOrderGoods;
import com.tennetcn.common.logical.wechat.service.IWechatOrderGoodsService;
import com.tennetcn.common.logical.wechat.service.IWechatOrderService;
import com.tennetcn.common.message.WechatLoginModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DESedeCoder;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.IPUtils;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.common.utils.MD5Utils;
import com.tennetcn.component.wechat.BaseWechat;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;


@Controller
@RequestMapping(value="/wechat/cust/customerIden/")
public class CustomerIdenWechat extends BaseWechat{
	
	@Override
	public String getRoutePath() {
		return "areas/wechat/cust/customerIden/";
	}
	 
	private IAccountInfoService accountInfoService;
	private IActiTaskService actiTaskService;
	private IGoldenBeanDetailService goldenBeanDetailService;
	private IAppRemindMessageService appRemindMessageService;
	public IAppRemindMessageService getAppRemindMessageService() {
		return appRemindMessageService;
	}
	@Resource
	public void setAppRemindMessageService(IAppRemindMessageService appRemindMessageService) {
		this.appRemindMessageService = appRemindMessageService;
	}
	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}
	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}

	public IActiTaskService getActiTaskService() {
		return actiTaskService;
	}
	@Resource
	public void setActiTaskService(IActiTaskService actiTaskService) {
		this.actiTaskService = actiTaskService;
	}

	public IGoldenBeanDetailService getGoldenBeanDetailService() {
		return goldenBeanDetailService;
	}
	@Resource
	public void setGoldenBeanDetailService(IGoldenBeanDetailService goldenBeanDetailService) {
		this.goldenBeanDetailService = goldenBeanDetailService;
	}
	
	private IWithdrawParamService withdrawParamService;

	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}

	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	private IWechatOrderGoodsService wechatOrderGoodsService;

	public IWechatOrderGoodsService getWechatOrderGoodsService() {
		return wechatOrderGoodsService;
	}
	
	@Resource
	public void setWechatOrderGoodsService(IWechatOrderGoodsService wechatOrderGoodsService) {
		this.wechatOrderGoodsService = wechatOrderGoodsService;
	}

	private IWechatOrderService wechatOrderService;
	
	
	public IWechatOrderService getWechatOrderService() {
		return wechatOrderService;
	}

	@Resource
	public void setWechatOrderService(IWechatOrderService wechatOrderService) {
		this.wechatOrderService = wechatOrderService;
	}


	private ICustomerService customerService;
	
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	private IRedEnvelopeRecordService redEnvelopeRecordService;
	
	public IRedEnvelopeRecordService getRedEnvelopeRecordService() {
		return redEnvelopeRecordService;
	}

	@Resource
	public void setRedEnvelopeRecordService(
			IRedEnvelopeRecordService redEnvelopeRecordService) {
		this.redEnvelopeRecordService = redEnvelopeRecordService;
	}

	
	private ISmsSendService smsSender;
	
	public ISmsSendService getSmsSendService() {
		return smsSender;
	}
	
	@Resource
	public void setSmsSendService(ISmsSendService smsSender) {
		this.smsSender = smsSender;
	}
	
	private final String registerNowViewName = "registerNow";
	private final String registerResultViewName = "registerResult";
	private final String joinEntrepreneurViewName = "joinEntrepreneur";
	private final String entrepreneurProtocolViewName = "entrepreneurProtocol";
	private final String sendMessageViewName = "sendMessage";
	private final String updateLevelViewName = "updateLevel";
	private final String checkPhoneExistedViewName = "checkPhoneExisted";
	private final String getCustomerByPhoneViewName = "getCustomerByPhone";
	private final String retrievePasswordViewName = "retrievePassword";
	private final String updatePasswordViewName = "updatePassword";
	private final String getCustomerNowByPhoneViewName = "getCustomerNowByPhone";
	private final String checkCodeViewName = "checkCode";
	
	@ResponseBody
	@RequestMapping(value = checkCodeViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String checkCode(Model model,String code,HttpServletRequest request) {
		if(!StringUtils.isEmpty(code)){
			String matchCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
			Date sendTime = (Date)request.getSession().getAttribute("sendTime");
			if(sendTime.getTime()-DateUtils.getCurrent().getTime()>5*60*1000){
				return "expire";
			}
			if(!code.equals(matchCode)){
				return "error";
			}
			return String.valueOf(true);
		}
		return String.valueOf(false);
	}

	@RequestMapping(value = retrievePasswordViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String retrievePassword(Model model) {
		
		return view(retrievePasswordViewName);
	}
	
	@ResponseBody
	@RequestMapping(value = updatePasswordViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String updatePassword(Model model,String newPassword, HttpServletRequest request,String customerId,String code){
		if(!StringUtils.isEmpty(code)){
			String matchCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
			Date sendTime = (Date)request.getSession().getAttribute("sendTime");
			if(sendTime.getTime()-DateUtils.getCurrent().getTime()>5*60*1000){
				return "expire";
			}
			if(!code.equals(matchCode)){
				return "error";
			}
		}
		Boolean result = false;
		if(!(StringUtils.isEmpty(newPassword)&&StringUtils.isEmpty(customerId))){
			String pwd=newPassword;
			String md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
			String password = DESedeCoder.encrypt(md5Pwd);
			String unionMark = DESedeCoder.encrypt(pwd);
			result = customerService.updatePassword(password, customerId, unionMark);	
		}
		return String.valueOf(result);
	}
	
	@RequestMapping(value = registerNowViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String registerNow(Model model) {
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		Customer customer=(Customer)loginModel.get(AresManageContainer.customer_account_info);
		model.addAttribute("customer", customer);
		
		return view(registerNowViewName);
	}
	
	@ResponseBody
	@RequestMapping(value = sendMessageViewName, method = { RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
	public String sendMessage(String phone, Model model, HttpServletRequest request) {
		String ipAddress = IPUtils.getIpAddr(request);
		String verifyCode = smsSender.sendVerifyCode(phone, ipAddress);
		
		HttpSession session = request.getSession();
		session.setAttribute("verifyCode", verifyCode);
		session.setAttribute("sendTime", DateUtils.getCurrent());
		
		return String.valueOf(true);
	}

	@ResponseBody
	@RequestMapping(value = checkPhoneExistedViewName, method = { RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
	public String checkPhoneExisted(String phone, Model model) {
		return String.valueOf(customerService.queryPhoneExisted(phone));		
	}
	
	@ResponseBody
	@RequestMapping(value = getCustomerByPhoneViewName, method = { RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
	public String getCustomerByPhone(String phone, Model model) {
		Customer customer=customerService.queryModelByPhone(phone);
		if(customer==null){
			return "";
		}
		return JsonUtils.toJson(customer);
	}
	
	@ResponseBody
	@RequestMapping(value = getCustomerNowByPhoneViewName, method = { RequestMethod.GET, RequestMethod.POST}, produces = "text/plain;charset=utf-8")
	public String getCustomerNowByPhone(Model model,String phone){
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		Customer loginCustomer = customerService.queryModelByOpenId(loginModel.getOpenId());
		Customer customer=customerService.queryModelByPhone(phone);
		if(customer!=null){
			if(customer.getId().equals(loginCustomer.getId())){
				return JsonUtils.toJson(customer);
			}
		}
		
		return "";
	}
	
	@ResponseBody
	@RequestMapping(value = registerResultViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String registerResult(Model model, HttpServletRequest request, Customer customer,String code) {

		if(!StringUtils.isEmpty(code)){
			String matchCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
			System.err.println(matchCode);
			Date sendTime = (Date)request.getSession().getAttribute("sendTime");
			if(sendTime.getTime()-DateUtils.getCurrent().getTime()>5*60*1000){
				return "expire";
			}
			if(!code.equals(matchCode)){
				return "error";
			}
		}
		
		boolean result=customerService.updateRegister(customer);
		
		if(result){
			updateLoginModel();
		}
		return String.valueOf(result);
	}
	
	@RequestMapping(value = joinEntrepreneurViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String joinEntrepreneur(Model model) {
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		Customer customer= customerService.queryModel(loginModel.getUserId());
		model.addAttribute("customer", customer);
		return view(joinEntrepreneurViewName);
	}
	
	@RequestMapping(value = entrepreneurProtocolViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String entrepreneurProtocol(Model model) {
		return view(entrepreneurProtocolViewName);
	}
	
	@ResponseBody
	@RequestMapping(value = updateLevelViewName, method = { RequestMethod.GET, RequestMethod.POST})
	public String updateLevel(Model model,Customer customer,String tradeNo,String code,HttpServletRequest request) {
		
		if(!StringUtils.isEmpty(code)){
			String matchCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
			System.err.println(matchCode);
			if(!code.equals(matchCode)){
				return String.valueOf(false);
			}
		}
		
		if(!StringUtils.isEmpty(customer.getPassword())){
			String pwd=customer.getPassword();
			String md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
			customer.setPassword(DESedeCoder.encrypt(md5Pwd));
			customer.setUnionMark(DESedeCoder.encrypt(pwd));
		}
		if(!StringUtils.isEmpty(customer.getRegion())){
			customer.setUpdateRegionDate(DateUtils.getCurrent());
		}
		
		if(CustomerLevel.maker.equals(customer.getLevel())){
			customer.setJoinMakerDate(DateUtils.getCurrent());
		}
		if(CustomerLevel.highMaker.equals(customer.getLevel())){
			customer.setJoinHighMakerDate(DateUtils.getCurrent());
		}
		
		if("1".equals(customer.getRefereeIdentity())){
			customer.setRefereeIdentity(1);
		}
		boolean result=customerService.updateCustomerByJoinMaker(customer);
		if(result){
			//重新更新一下customer_account_info
			updateLoginModel();
			WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		
			//业务逻辑判断
			if(!StringUtils.isEmpty(tradeNo)){
				WechatOrder wechatOrder = wechatOrderService.queryModel(tradeNo);
			
				goodsMarkJudge(loginModel.getOpenId(),wechatOrder);	
			}
			
		}
		return String.valueOf(result);
	}
	
	private void updateLoginModel(){
		//重新更新一下customer_account_info
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		Customer customer=customerService.queryModel(loginModel.getUserId());
		loginModel.put(AresManageContainer.customer_account_info, customer);
	}
	

	
	
	//根据订单判断购买的商品中的goodsmark来判定后续的业务操作
	private void goodsMarkJudge(String openId,WechatOrder wechatOrder){
		//初步考虑，wechatOrder不会为空
		String orderId=wechatOrder.getTradeNo();
		WechatOrderGoodsSearch search=new WechatOrderGoodsSearch();
		search.setOrderId(orderId);
		List<WechatOrderGoods> wechatOrderGoods=wechatOrderGoodsService.queryList(search);
		
		boolean maker=Enumerable.init(wechatOrderGoods).any(wog->{return GoodsMark.maker.equals(wog.getGoodsMark());});
		
		if(maker){
			makerJudge(openId,wechatOrder);
		}
		boolean highMaker=Enumerable.init(wechatOrderGoods).any(wog->{return GoodsMark.highMaker.equals(wog.getGoodsMark());});
		if(highMaker){
			highMakerJudge(openId,wechatOrder);
		}
	}
	
	
	/*//判断这个人加入创客时有没有领红包
	private void sendJoinRedEnvelopeRecord(Customer joinCustomer,Customer refereeCustomer,WechatOrder wechatOrder){
		String id = "";
		if(!StringUtils.isEmpty(refereeCustomer)){
			String category =  RedEnvelopeRecordType.joinByrefreeCustomer;
			RedEnvelopeRecord redEnvelopeRecord = redEnvelopeRecordService.queryModelByCategory(joinCustomer.getId(),joinCustomer.getId(), refereeCustomer.getId(), category);
			
			if(redEnvelopeRecord==null){
				//yes代表他绑定上级还没有奖励红包
				
				//生成一条红包记录
				redEnvelopeRecord = new RedEnvelopeRecord();
				String redEnvelopeRecordId = CommonUtils.getKeyId();
				redEnvelopeRecord.setId(redEnvelopeRecordId);
				redEnvelopeRecord.setReceiverId(joinCustomer.getId()); 
				redEnvelopeRecord.setRefreeId(refereeCustomer.getId());
				redEnvelopeRecord.setRefreeLevel(refereeCustomer.getLevel());
				redEnvelopeRecord.setJoinId(joinCustomer.getId());
				redEnvelopeRecord.setJoinLevel(CustomerLevel.maker);
				redEnvelopeRecord.setRedMoney(RedEnvelopeRecordType.joinByrefreeCustomerMoney);
				redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
				redEnvelopeRecord.setCategory(RedEnvelopeRecordType.joinByrefreeCustomer);
				redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
				redEnvelopeRecord.setTradeNo(wechatOrder.getTradeNo());
				redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
				redEnvelopeRecord.setModelStatus(ModelStatus.add);
						
				//如果红包记录添加成功
				if(redEnvelopeRecordService.applyChange(redEnvelopeRecord)){
					id = redEnvelopeRecordId;
				}
			}
		}
			WechatTemplateManager.sendOrderPaySuccess(wechatOrder.getOpenId(), wechatOrder.getTotalFee(), wechatOrder.getName(),id);
	}*/
	
	//升级到初创
	private boolean makerJudge(String openId,WechatOrder wechatOrder){
		//js也能接收到回调，这里的判断先放到js的提交里面去更新创客的信息，这里只处理
		//if(customerService.updateMaker(openId)){
		
		//只发送通知
		Customer customer=customerService.queryModelByOpenId(openId);
		Customer refereeCustomer=null;
		refereeCustomer = customerService.queryRefereeModelByOpenId(openId);

		//发送订单通知
		//sendJoinRedEnvelopeRecord(customer, refereeCustomer, wechatOrder);
		WechatTemplateManager.sendOrderPaySuccess(wechatOrder.getOpenId(), wechatOrder.getTotalFee(), wechatOrder.getName(),null);
		

		//APP发送订单通知(给当前人)
		JpushClient.sendorderPaySuccessApp(wechatOrder.getTotalFee(), customer,appRemindMessageService);
		
		//上级为空或者为未关注状态
		if(refereeCustomer==null||!AttentionStatus.attention.equals(refereeCustomer.getAttentionStatus())){
			return true;
		}		
		// 上级是初创或高创，都给通知
		if(CustomerLevel.maker.equals(refereeCustomer.getLevel()) || CustomerLevel.highMaker.equals(refereeCustomer.getLevel())) {
			String id = "";
			//订单支付的钱等于加入当前创客等级的钱才给上级发红包
			if(wechatOrder.getTotalFee()==RedEnvelopeRecordType.joinMakerMoney){
//				//判断上级招募创客逻辑
//				updataGoldenBean(refereeCustomer);
				//生成红包
				RedEnvelopeRecord redEnvelopeRecord  = redEnvelopeRecordService.queryModelByCategory(refereeCustomer.getId(), customer.getId(), refereeCustomer.getId(),RedEnvelopeRecordType.recommendMaker);
				
				if(redEnvelopeRecord==null){
					double redMoney=0.0;
					redEnvelopeRecord = new RedEnvelopeRecord();
					String redEnvelopeRecordId = CommonUtils.getKeyId(); 				
					redEnvelopeRecord.setId(redEnvelopeRecordId);
					redEnvelopeRecord.setReceiverId(refereeCustomer.getId());
					redEnvelopeRecord.setRefreeId(refereeCustomer.getId());
					redEnvelopeRecord.setRefreeLevel(refereeCustomer.getLevel());
					redEnvelopeRecord.setJoinId(customer.getId());
					redEnvelopeRecord.setJoinLevel(CustomerLevel.maker);
					/*初创推荐初创*/
					if(CustomerLevel.maker.equals(refereeCustomer.getLevel())){
						WithdrawParam wp = withdrawParamService.queryModelByHelpCode("makerToMaker");
						redMoney = wp.getParam();
					}
					/*高创推荐初创*/
					if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel())){
						WithdrawParam wp = withdrawParamService.queryModelByHelpCode("highMakerToMaker");
						redMoney = wp.getParam();
					}
					/*合伙人推荐初创*/
					if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel()) && "city".equals(refereeCustomer.getHonor())){
						WithdrawParam wp = withdrawParamService.queryModelByHelpCode("cityToMaker");
						redMoney = wp.getParam();
					}
					
					/*double redMoney = getRedEnvelope(RedEnvelopeRecordType.recommendMaker);
					redEnvelopeRecord.setRedMoney(redMoney);*/
					redEnvelopeRecord.setRedMoney(redMoney);
					redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
					redEnvelopeRecord.setCategory(RedEnvelopeRecordType.recommendMaker);
					redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
					redEnvelopeRecord.setTradeNo(wechatOrder.getTradeNo());
					redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
					redEnvelopeRecord.setModelStatus(ModelStatus.add);
					
					if(redEnvelopeRecordService.applyChange(redEnvelopeRecord)){
						id = redEnvelopeRecordId;
					}

				}
			}	
			WechatTemplateManager.sendUpdateLevel(refereeCustomer.getOpenId(), customer,CustomerLevel.maker,null,id);

			//APP发送通知（给当前登录人的上一级）
			JpushClient.sendUpdateLevelApp(refereeCustomer.getUserIdentity(), customer, refereeCustomer, null,id,appRemindMessageService,CustomerLevel.maker);

		}
			if(StringUtils.isEmpty(refereeCustomer.getRefereeId())){
				return true;
			}
			Customer refereeTwoCustomer=customerService.queryModel(refereeCustomer.getRefereeId());
			if(refereeTwoCustomer==null||!AttentionStatus.attention.equals(refereeTwoCustomer.getAttentionStatus())){
				return true;
			}	
			// 判断上级的上级是创客就给通知
			if (CustomerLevel.maker.equals(refereeTwoCustomer.getLevel())||CustomerLevel.highMaker.equals(refereeTwoCustomer.getLevel())) {
				WechatTemplateManager.sendUpdateLevel(refereeTwoCustomer.getOpenId(), customer,CustomerLevel.maker,refereeCustomer,null);

			//app发信息（给当前登录人的上二级）
			JpushClient.sendUpdateLevelApp(refereeTwoCustomer.getUserIdentity(), customer, refereeCustomer, refereeTwoCustomer,null,appRemindMessageService,CustomerLevel.maker);
			}
		return true;
	}
	
	//升级到高创
	private boolean highMakerJudge(String openId,WechatOrder wechatOrder){
		//js也能接收到回调，这里的判断先放到js的提交里面去更新创客的信息，这里只处理
		//if(customerService.updateHighMaker(openId)){
		
		//只发送通知
		Customer customer=customerService.queryModelByOpenId(openId);
		Customer refereeCustomer=null;
		refereeCustomer = customerService.queryRefereeModelByOpenId(openId);
		
		//发送订单通知
		//sendJoinRedEnvelopeRecord(customer, refereeCustomer, wechatOrder);
		WechatTemplateManager.sendOrderPaySuccess(wechatOrder.getOpenId(), wechatOrder.getTotalFee(), wechatOrder.getName(),null);
		
		//APP发送订单通知(给当前人)
		JpushClient.sendorderPaySuccessApp(wechatOrder.getTotalFee(), customer,appRemindMessageService);
		
		if(refereeCustomer==null||!AttentionStatus.attention.equals(refereeCustomer.getAttentionStatus())){
			return true;
		}
		// 上级是创客就给通知
		if (CustomerLevel.maker.equals(refereeCustomer.getLevel())||CustomerLevel.highMaker.equals(refereeCustomer.getLevel())) {
				String id = "";
				//订单支付的金额等于加入高创的金额才发送红包
				if(wechatOrder.getTotalFee()==RedEnvelopeRecordType.joinHighmakerMoney||wechatOrder.getTotalFee()==RedEnvelopeRecordType.makerToHighmakerMoney){
					
//					//判断上级招募创客逻辑
//					updataGoldenBean(refereeCustomer);
					
					String category = "";
					double redMoney=0.0;
					if(wechatOrder.getTotalFee()==RedEnvelopeRecordType.joinHighmakerMoney){
						category = RedEnvelopeRecordType.recommendHighmaker;
						/*初创推荐高创*/
						if(CustomerLevel.maker.equals(refereeCustomer.getLevel())){
							WithdrawParam wp = withdrawParamService.queryModelByHelpCode("makerToHighMaker");
							redMoney = wp.getParam();
						}
						/*高创推荐高创*/
						if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel())){
							WithdrawParam wp = withdrawParamService.queryModelByHelpCode("highMakerToHighMaker");
							redMoney = wp.getParam();
						}
						/*合伙人推荐高创*/
						if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel()) && "city".equals(refereeCustomer.getHonor())){
							WithdrawParam wp = withdrawParamService.queryModelByHelpCode("cityToHighMaker");
							redMoney = wp.getParam();
						}
					}else if(wechatOrder.getTotalFee()==RedEnvelopeRecordType.makerToHighmakerMoney){
						category = RedEnvelopeRecordType.makerToHighmaker;
						if(CustomerLevel.maker.equals(refereeCustomer.getLevel())){
							WithdrawParam wp = withdrawParamService.queryModelByHelpCode("makerToMakerToHighMaker");
							redMoney = wp.getParam();
						}
						/*高创推荐高创*/
						if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel())){
							WithdrawParam wp = withdrawParamService.queryModelByHelpCode("highMakerToMakerToHighMaker");
							redMoney = wp.getParam();
						}
						/*合伙人推荐高创*/
						if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel()) && "city".equals(refereeCustomer.getHonor())){
							WithdrawParam wp = withdrawParamService.queryModelByHelpCode("cityToMakerToHighMaker");
							redMoney = wp.getParam();
						}
					}
					
					
					
					/*redMoney = getRedEnvelope(category);*/
	
					RedEnvelopeRecord redEnvelopeRecord  = redEnvelopeRecordService.queryModelByCategory(refereeCustomer.getId(), customer.getId(), refereeCustomer.getId(),category);
					if(redEnvelopeRecord==null){
						redEnvelopeRecord = new RedEnvelopeRecord();
						String redEnvelopeRecordId = CommonUtils.getKeyId(); 				
						redEnvelopeRecord.setId(redEnvelopeRecordId);
						redEnvelopeRecord.setReceiverId(refereeCustomer.getId());
						redEnvelopeRecord.setRefreeId(refereeCustomer.getId());
						redEnvelopeRecord.setRefreeLevel(refereeCustomer.getLevel());
						redEnvelopeRecord.setJoinId(customer.getId());
						redEnvelopeRecord.setJoinLevel(CustomerLevel.highMaker);
						redEnvelopeRecord.setRedMoney(redMoney);
						redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
						redEnvelopeRecord.setCategory(category);
						redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
						redEnvelopeRecord.setTradeNo(wechatOrder.getTradeNo());
						redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
						redEnvelopeRecord.setModelStatus(ModelStatus.add);
						
						if(redEnvelopeRecordService.applyChange(redEnvelopeRecord)){
							id = redEnvelopeRecordId;
						}	
						
					}
				}		
				WechatTemplateManager.sendUpdateLevel(refereeCustomer.getOpenId(), customer,CustomerLevel.highMaker,null,id);
				//APP发送通知（给当前登录人的上一级）
				JpushClient.sendUpdateLevelApp(refereeCustomer.getUserIdentity(), customer, refereeCustomer, null,id,appRemindMessageService,CustomerLevel.highMaker);	
		}
			
			if(StringUtils.isEmpty(refereeCustomer.getRefereeId())){
				return true;
			}
			Customer refereeTwoCustomer=customerService.queryModel(refereeCustomer.getRefereeId());
			if(refereeTwoCustomer==null||!AttentionStatus.attention.equals(refereeTwoCustomer.getAttentionStatus())){
				return true;
			}
			// 判断上级的上级是创客就给通知
			if (CustomerLevel.maker.equals(refereeTwoCustomer.getLevel())||CustomerLevel.highMaker.equals(refereeTwoCustomer.getLevel())) {
				WechatTemplateManager.sendUpdateLevel(refereeTwoCustomer.getOpenId(), customer,CustomerLevel.highMaker,refereeCustomer,null);
				//app发信息（给当前登录人的上二级）
				JpushClient.sendUpdateLevelApp(refereeTwoCustomer.getUserIdentity(), customer, refereeCustomer, refereeTwoCustomer,null,appRemindMessageService,CustomerLevel.highMaker);
			}
		
		return true;
	}

	/*private boolean updataGoldenBean(Customer refereeCustomer) {
		// 判断上级今日是否招募1名初创，如果有就发500金豆
		if (customerService.queryCountDayMakers(refereeCustomer.getId())==1) {
			if(goldenBeanDetailService.addGoldenBeanDetail(TaskId.dayMaker, 500, GoldenBeanType.dayMaker, refereeCustomer.getId())){
				return true;
			}
		}

		// 判断上级本周是否招募到3位创客，如果有就发1000金豆
		if (customerService.queryCountWeekMakers(refereeCustomer.getId())==3) {
			if(goldenBeanDetailService.addGoldenBeanDetail(TaskId.weekMaker, 1000, GoldenBeanType.weekMaker, refereeCustomer.getId())){
				return true;
			}
			
		}

		// 判断上级本月是否招募到10位创客，如果有就发2000金豆
		if (customerService.queryCountMonthMakers(refereeCustomer.getId())==10) {
			if(goldenBeanDetailService.addGoldenBeanDetail(TaskId.monthMaker, 2000, GoldenBeanType.monthMaker, refereeCustomer.getId())){
				return true;
			}
		}
		return false;
	}*/
	
	/*不要注册会员就不发会员消息
	 	private boolean joinRegister(String openId){
		//只发送通知
		Customer customer=customerService.queryModelByOpenId(openId);
		Customer refereeCustomer=customerService.queryRefereeModelByOpenId(openId);
		if(refereeCustomer==null||!AttentionStatus.attention.equals(refereeCustomer.getAttentionStatus())){return true;}
		
		// 上级是初创或高创，都给通知
		if (CustomerLevel.maker.equals(refereeCustomer.getLevel()) || CustomerLevel.highMaker.equals(refereeCustomer.getLevel())) {
			WechatTemplateManager.sendUpdateLevel(refereeCustomer.getOpenId(), customer,CustomerLevel.vip,null,null);
		}

		Customer refereeTwoCustomer=customerService.queryModel(refereeCustomer.getRefereeId());
		if(refereeTwoCustomer==null||!AttentionStatus.attention.equals(refereeTwoCustomer.getAttentionStatus())){return true;}
		
		// 判断上级的上级是高创就给通知
		if (CustomerLevel.maker.equals(refereeTwoCustomer.getLevel())||CustomerLevel.highMaker.equals(refereeTwoCustomer.getLevel())) {
			WechatTemplateManager.sendUpdateLevel(refereeTwoCustomer.getOpenId(),customer,CustomerLevel.vip,refereeCustomer,null);
		}
		return true;
	}*/
	
	/*private Double getRedEnvelope(String category){
		double random = Math.random();
		double balance = 0.00;
		
		if(random>=0 && random<=0.25){
			if(category.equals(RedEnvelopeRecordType.recommendMaker)){
				balance = RedEnvelopeRecordType.recommendMakerRedMoney1;
			}else if(category.equals(RedEnvelopeRecordType.recommendHighmaker)){
				balance = RedEnvelopeRecordType.recommendHighMakerRedMoney1;
			}else if(category.equals(RedEnvelopeRecordType.makerToHighmaker)){
				balance = RedEnvelopeRecordType.makerToHighmakerRedMoney1;
			}
		}else if(random<=0.75){
			if(category.equals(RedEnvelopeRecordType.recommendMaker)){
				balance = RedEnvelopeRecordType.recommendMakerRedMoney2;
			}else if(category.equals(RedEnvelopeRecordType.recommendHighmaker)){
				balance = RedEnvelopeRecordType.recommendHighMakerRedMoney2;
			}else if(category.equals(RedEnvelopeRecordType.makerToHighmaker)){
				balance = RedEnvelopeRecordType.makerToHighmakerRedMoney2;
			}
		}else if(random<=1.00){
			if(category.equals(RedEnvelopeRecordType.recommendMaker)){
				balance = RedEnvelopeRecordType.recommendMakerRedMoney3;
			}else if(category.equals(RedEnvelopeRecordType.recommendHighmaker)){
				balance = RedEnvelopeRecordType.recommendHighMakerRedMoney3;
			}else if(category.equals(RedEnvelopeRecordType.makerToHighmaker)){
				balance = RedEnvelopeRecordType.makerToHighmakerRedMoney3;
			}
		}
	
		return balance;
	}
	*/

	
	
}
